package com.acooly.module.openapi.client.provider.yuejb.marshal;

import com.acooly.core.utils.Strings;
import com.acooly.core.utils.net.HttpResult;
import com.acooly.module.openapi.client.api.exception.ApiClientException;
import com.acooly.module.openapi.client.api.marshal.ApiUnmarshal;
import com.acooly.module.openapi.client.api.message.MessageFactory;
import com.acooly.module.openapi.client.api.util.Jsons;
import com.acooly.module.openapi.client.provider.yuejb.YueJBConstants;
import com.acooly.module.openapi.client.provider.yuejb.domain.YueJBResponse;
import com.acooly.module.openapi.client.provider.yuejb.utils.DomainObject2Map;
import com.acooly.module.openapi.client.provider.yuejb.utils.SignUtils;
import com.acooly.module.safety.Safes;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Map;

/**
 * Created by ouwen@yiji.com} on 2017/11/7.
 */
@Slf4j
@Service
public class YueJBResponseUnmarshal extends YueJBMarshallSupport implements ApiUnmarshal<YueJBResponse, HttpResult> {

    @Resource(name = "yueJBMessageFactory")
    private MessageFactory messageFactory;

    @Override
    public YueJBResponse unmarshal(HttpResult message, String serviceName) {
        YueJBResponse yueJBResponse;
        try {
            String plain = message.getBody();
            log.info("响应报文:{}", message.getBody());
            yueJBResponse = (YueJBResponse) messageFactory.getResponse(serviceName);
            yueJBResponse = Jsons.parse(plain, yueJBResponse.getClass());
            yueJBResponse.setService(serviceName);
            yueJBResponse.setPartnerId(getProperties().getPartnerId());
            String signature = yueJBResponse.getSign();//渠道返回sign
            log.debug("响应签名:{}", signature);
            try {
                if (Strings.isEmpty(signature)) {
                    return yueJBResponse;
                }
                Map<String, String> requestData = DomainObject2Map.tomap(yueJBResponse);
                //签名
                String waitingForSign = SignUtils.buildWaitingForSign(requestData);
                log.debug("代签名字符串:{}", waitingForSign);
                Safes.getSigner(YueJBConstants.SIGN_TYPE).verify(waitingForSign, openAPIClientYueJBProperties.getSign(), signature);
            } catch (Exception e) {
                log.error("请求报文处理异常：" + e.getMessage());
                yueJBResponse.setStatus("FAIL");
                yueJBResponse.setCode("FAIL");
                yueJBResponse.setMessage(e.getMessage());
                yueJBResponse.setDescription(e.getMessage());
                return yueJBResponse;
            }
        } catch (Exception e) {
            throw new ApiClientException("解析响应报文错误:" + e.getMessage());
        }
        return yueJBResponse;
    }
}
